package com.mantru.iotpot.Cook.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.mantru.iotpot.DateClass.ingredients;
import com.mantru.iotpot.R;

import java.util.List;

public class FoodDetailsAdapter extends RecyclerView.Adapter<FoodDetailsAdapter.ViewHolder> {
    private List<ingredients> step;
    private Context context;
    private OnButtonClickListener listener; // 定义接口
    private int selectedPosition = 0; // 添加一个变量来跟踪当前选中的位置

    // 定义接口
    public interface OnButtonClickListener {
        void onButtonClick(String specId);
    }

    public FoodDetailsAdapter(Context context, List<ingredients> step, OnButtonClickListener listener) {
        this.context = context;
        this.step = step;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.food_details_button, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ingredients item = step.get(position);
        holder.button.setText(item.getCopies_qty() + "份" + item.getWeight() + "g");
        holder.button.setTag(item.getSpec_id());
        final int position1 = position;
        // 设置点击监听器
        holder.button.setOnClickListener(v -> {
            if (listener != null) {
                listener.onButtonClick(item.getSpec_id());
            }
            // 更新选中位置并刷新适配器
            selectedPosition = position1;
            notifyDataSetChanged();
        });
        // 根据是否选中来设置背景资源
        if (position1 == selectedPosition) {
            holder.button.setBackgroundResource(R.drawable.button12);
        } else {
            holder.button.setBackgroundResource(R.drawable.button14);
        }
    }

    @Override
    public int getItemCount() {
        return step.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        Button button;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            button = itemView.findViewById(R.id.food_details_button);
        }
    }
}
